<template>
  <div>
    <GdMapDlg ref="mapDlg"></GdMapDlg>
    <a-modal
      :title="title"
      :visible="visible"
      @ok="handleOk"
      @cancel="visible = false"
    >
      <a-modal
        title="Title"
        :visible="showParamDlg"
        @ok="setParamOK"
        @cancel="showParamDlg = false"
      >
        <a-input v-model="paramValue"></a-input>
      </a-modal>
      <a-form-model :label-col="{ span: 4 }" :wrapper-col="{ span: 12 }">
        <a-form-model-item
          ref="count"
          label="个数"
          prop="count"
          v-if="item.isNew"
        >
          <a-input-number
            id="inputNumber"
            v-model="count"
            :min="1"
            :max="100"
            style="width: 100%"
          ></a-input-number>
        </a-form-model-item>
      </a-form-model>
      <a-tabs :default-active-key="akey" v-model="akey">
        <a-tab-pane key="0" tab="基本信息">
          <a-form-model
            ref="ruleForm"
            :rules="rules"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 12 }"
            :model="item"
          >
            <a-form-model-item ref="model_id" label="物模型" prop="物模型">
              <a-select
                v-model="item.model_id"
                :disabled="!item.isNew"
                placeholder="请选择"
                @select="onSelectModel"
              >
                <a-select-option v-for="d in tmodels" :key="d.uid">
                  {{ d.s_name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item ref="s_name" label="名称" prop="s_name">
              <a-input
                v-model="item.s_name"
                @blur="
                  () => {
                    $refs.s_name.onFieldBlur();
                  }
                "
              />
            </a-form-model-item>
            <a-form-model-item
              ref="uid"
              label="id"
              prop="uid"
              v-if="item.uid != ''"
            >
              <a-input v-model="item.uid" :disabled="!item.isNew" />
            </a-form-model-item>
            <a-form-model-item label="接入点">
              <a-select
                v-model="item.proxy_thing_id"
                style="width: 70%"
                default-value=""
              >
                <a-select-option
                  v-for="edge in edges"
                  :key="edge.uid"
                  :value="edge.uid"
                >
                  {{ edge.s_name }}
                </a-select-option>
              </a-select>
              <a-button @click="refreshEdges">刷新</a-button>
            </a-form-model-item>
            <a-form-model-item ref="status" label="开通状态" prop="status">
              <a-select v-model="item.status_used" default-value="1">
                <a-select-option value="-1">施工中</a-select-option>
                <a-select-option value="1">启用</a-select-option>
                <a-select-option value="0">停用</a-select-option>
                <a-select-option value="-2">未知</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="采集模板">
              <a-select v-model="pickTemplateName" style="width: 200px">
                <a-select-option
                  v-for="item in PickTemplates"
                  :key="item.s_name"
                  :value="item.s_name"
                  >{{ item.s_name }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="点位编号">
              <a-input v-model="item.business_id" />
            </a-form-model-item>
          </a-form-model>
          <a-form-model>
            <a-form-model-item label="地理位置">
              <div style="margin-left: 40px">
                <a-space>
                  经度<a-input v-model="item.lon" style="width: 80px"></a-input>
                  纬度<a-input v-model="item.lat" style="width: 80px"></a-input>
                  <a-button @click="cfgGPS">配置</a-button>
                </a-space>
              </div>
            </a-form-model-item>
          </a-form-model>
        </a-tab-pane>
        <a-tab-pane key="1" tab="设备参数">
          <a-table
            :data-source="item.params"
            :columns="pcolumns"
            :rowKey="(record) => record.param_id"
          >
            <template slot="operation" slot-scope="text, record, index">
              <a @click="() => edit(record, index)">修改</a>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" tab="设备协议服务">
          <a-radio-group
            :options="protocols"
            v-model="item.protocol_path"
          ></a-radio-group>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>
<script>
import { get, update } from "@/services/crud";
const pcolumns = [
  {
    title: "名称",
    dataIndex: "name",
    width: "25%",
  },
  {
    title: "id",
    dataIndex: "param_id",
  },
  {
    title: "值",
    dataIndex: "param_value",
    width: "40%",
  },
  {
    title: "operation",
    dataIndex: "operation",
    scopedSlots: { customRender: "operation" },
  },
];
import GdMapDlg from "@/components/map/GdMapDlg.vue";
export default {
  components: {
    GdMapDlg,
  },
  computed: {
    tmodels() {
      return this.$store.state.tmodel.tmodels;
    },
    title() {
      return this.item.isNew ? "新增被监控对象" : "编辑被监控对象";
    },
    edges() {
      let edges = [];
      if (this.$store.state.thingView.edges) {
        edges = Object.assign(edges, this.$store.state.thingView.edges);
      }
      if (!edges) {
        edges = [];
      }
      if (process.env.VUE_APP_TYPE !== "edge") {
        edges.push({ uid: "", s_name: "直连" });
      }

      return edges;
    },
  },
  data() {
    return {
      akey: 0,
      pcolumns,
      visible: false,
      callback: null,
      owner: null,
      item: { params: [] },
      paramValue: "",
      paramIndex: 0,
      showParamDlg: false,
      curRecord: {},
      protocols: [],
      PickTemplates: [],
      count: 1,
      pickTemplateName:'',
      rules: {
        s_name: [
          {
            required: true,
            message: "名称不能为空，长度3-100",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    setGPS(map) {
      this.$set(this.item, "lon", "" + map.lon);
      this.$set(this.item, "lat", "" + map.lat);
    },
    cfgGPS() {
      this.$refs.mapDlg.ShowMapDlg(this.setGPS, this);
    },
    refreshEdges() {
      this.$store.dispatch("thingView/refreshEdges");
    },
    Show(callback, owner, item) {
      console.log("****************", item);
      this.callback = callback;
      this.owner = owner;
      this.paramValue = "";
      this.count = 1;
      this.protocols = [];
      const _this = this;
      this.refreshEdges();
      //this.$store.dispatch("tmodel/refreshTModels").then(() => {
      if(!item.pickTemplateName){
        item.pickTemplateName = ""
      }
      if (item.s_name == undefined) {
        item.s_name = "";
      }
      if (item.proxy_thing_id == undefined) {
        item.proxy_thing_id = "";
      }
      if (item.status_used == undefined) {
        item.status_used = 1;
      }
      if (item.uid && item.uid !== "" && !item.isNew) {
        //item.params = []
        get("thingparam", item.uid).then((res) => {
          if (res && res.data && res.data.result) {
            item.params = res.data.result;
            console.log("get params---------------", item);
          }
          _this.item = JSON.parse(JSON.stringify(item));
          if (item.model_id) {
            _this.onSelectModel(item.model_id);
          }

          get("tmodelprotocol", item.model_id).then((res2) => {
            if (res2 && res2.data && res2.data.result) {
              _this.protocols = res2.data.result.map((p) => {
                return { label: p.protocol_path, value: p.protocol_path };
              });
              _this.protocols.push({ label: "空白", value: "" });
              _this.protocols.push({ label: "模拟数据", value: "magical" });
            }
            _this.visible = true;
            _this.akey = "0";
          });
        });
      } else {
        _this.item = JSON.parse(JSON.stringify(item));
        _this.item.status_used = "1";
        _this.visible = true;
      }
      if (_this.item.isNew)
        if (_this.edges.length == 1) {
          //_this.item.proxy_thing_id = _this.edges[0].uid;
          _this.$set(item, "proxy_thing_id", _this.edges[0].uid);
        }
      get("pickTemplate", "all").then((res) => {
        this.PickTemplates = res?.data?.result;
        if (
          _this.PickTemplates == undefined ||
          !Array.isArray(this.PickTemplates)
        ) {
          _this.PickTemplates = [];
         
        }
         get("/devPicTemplate/" , item.uid).then((res) => {
            _this.pickTemplateName = res?.data?.result?.s_name;
            _this.item.pickTemplateName = _this.pickTemplateName
          })
      });

      //});
    },
    edit(record, index) {
      console.log("************", record);
      this.paramValue = record.param_value;
      this.curRecord = record;
      this.showParamDlg = true;
      this.paramIndex = index;
    },
    onSelectModel(val, refreshed) {
      const m = this.$store.state.tmodel.tmodelCache[val];
      if (!m && !refreshed) {
        let self = this;
        this.$store.dispatch("tmodel/refreshTModels").then(() => {
          self.onSelectModel(val, true);
        });
      }
      if (!m) {
        return;
      }
      let body = {};
      if (m.body && typeof m.body === "string") {
        body = JSON.parse(m.body);
      } else if (m.body) {
        body = m.body;
      }
      if (this.item.isNew) {
        this.item.params = [];
        this.item.lon = "";
        this.item.lat = "";
      }

      console.log("------------", body);
      if (body && body.params) {
        this.params = [];
        if (!this.item.params) {
          this.item.params = [];
        }
        body.params.forEach((p) => {
          const param = this.item.params.find((ip) => {
            return p.identifier == ip.param_id;
          });
          if (!param) {
            this.item.params.push({
              name: p.name,
              param_id: p.identifier,
              param_value: "",
            });
          } else {
            param.name = p.name;
          }
        });
      } else {
        this.item.params = [];
      }
      if (!this.item.s_name) {
        this.item.s_name = m.s_name;
      }
      let _this = this;
      get("tmodelprotocol", m.uid).then((res2) => {
        if (res2 && res2.data && res2.data.result) {
          _this.protocols = res2.data.result.map((p) => {
            return { label: p.protocol_path, value: p.protocol_path };
          });
          //_this.protocols.push("不选")
          _this.protocols.push({ label: "空白", value: "" });
        }
      });
    },
    setParamOK() {
      this.curRecord.param_value = this.paramValue;
      this.$set(this.item.params, this.paramIndex, this.curRecord);
      console.log("!!!!!!", this.curRecord);
      this.showParamDlg = false;
    },
    handleOk() {
      let self = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          self.handleOkImpl();
          return true;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    Close() {
      this.visible = false;
    },
    handleOkImpl() {
      if (this.item.s_name == "") {
        return;
      }
      if (this.callback) {
        if (typeof this.item.status_used === "string") {
          this.item.status_used = Number(this.item.status_used);
        }
        if (this.item.proxy_thing_id != "") {
          this.item.is_proxy = false;
        } else {
          this.item.is_proxy = true;
        }
        let result = this.callback(this.owner, this);
        if (result == true) {
          this.visible = false;
        } else {
          let self = this;
          if (result) {
            result?.finally(() => {
              if (self.pickTemplateName) {
                self.item.pickTemplateName = self.pickTemplateName
                update("/devPicTemplate", {
                  thing_id: self.item.uid,
                  pick_template_name: self.item.pickTemplateName,
                })
                  .then(() => {
                    self.visible = false;
                  })
                  .catch((err) => {
                    console.log(err);
                  });
              }
            });
          }
        }
      }
    },
  },
};
</script>
<style>
.ant-table-tbody > tr > td {
  background: rgba(255, 255, 255, 0) !important;
}
.ant-table-tbody > tr > td:hover {
  background: rgb(255, 255, 255) !important;
}

.ant-table-tbody > tr > td {
  background: rgba(255, 255, 255, 0) !important;
}
.ant-table-tbody > tr > td:hover {
  background: rgba(255, 255, 255, 0) !important;
}
</style>
